<template>
  <div id="indexMap-map"></div>
</template>
<script>
import '@/assets/map/ol/ol.css';
import { getProjection } from "@/map/projMap.js";
import Map from 'ol/Map';
import View from 'ol/View';
import VectorLayer from 'ol/layer/Vector';
import {Vector as VectorSource} from 'ol/source';
import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';
import WKT from 'ol/format/WKT';
import {boundingExtent} from 'ol/extent';
import {Fill, Stroke, Style, Icon, Circle as CircleStyle,Text} from 'ol/style';
import dingweiImg from '@/assets/map/image/newImage/blueMarker.png';

export default {
  name: "IndexMap",
  components: {

  },
  props:{
    xjAllDataArray: {//获取新建工程查询结果列表
      type: Array,
      required:false,
      default: []
    },
    jgAllDataArray: {//获取加固工程查询结果列表
      type: Array,
      required:false,
      default: []
    },
  },
  emits:["getMap"],
  data() {
    return {
      str: "indexMap",
      map: null,
      // center: [105, 34],
      // zoom: 4,
      center: [105, 27.5],
      zoom: 4,
      xjAllDataList:[],//查询结果列表
      xjAllDataVectorLayer:null,//查询结果图层
      jgAllDataList:[],//查询结果列表
      jgAllDataVectorLayer:null,//查询结果图层
    }
  },
  watch: {
    xjAllDataArray: {//获取新建工程查询结果列表
      handler: function(newVal,oldVal){
        //if(newVal!=oldVal){
          this.xjAllDataList = newVal;
          this.showXjAllDataList();////显示新建工程查询结果列表
        //}
      },
      immediate:true
    },
    jgAllDataArray: {//获取加固工程查询结果列表
      handler: function(newVal,oldVal){
        //if(newVal!=oldVal){
          this.jgAllDataList = newVal;
          this.showJgAllDataList();////显示加固工程查询结果列表
        //}
      },
      immediate:true
    },
  },
  created() {

  },
  mounted() {
    console.log("mounted");
    let that = this;
    //地图异步加载
    this.$nextTick(function(){
      console.log('地图异步加载');
      //地图异步加载
      setTimeout(() => {
        //初始化地图信息
        that.initMap();
      }, 200);
    });
  },
  beforeCreate() {//生命周期创建之前
    console.log("beforeCreate");
  },
  beforeMount() {//生命周期挂载之前
    console.log("beforeMount");
  },
  beforeUpdate() {//生命周期更新之前
    console.log("beforeUpdate");
  },
  updated() {//生命周期更新之后
    console.log("updated");
  },
  beforeDestroy() {//生命周期销毁之前
    console.log("beforeDestroy");
  },
  destroyed() {//生命周期销毁完成
    this.map = null;
    console.log("销毁地图");
  },
  activated() {//如果页面有keep-alive缓存功能激活，这个函数会触发
    console.log("activated-"+this.str);
    //自动获取地图div高度
    this.autodivheight();
    //浏览器窗口发生变化时同时变化DIV高度
    window.onresize=this.autodivheight;
  },
  deactivated() {//如果页面有keep-alive缓存功能停用，这个函数会触发
    console.log("deactivated-"+this.str);
    //取消浏览器窗口发生变化时同时变化DIV高度事件
    window.onresize = null;
  },
  methods: {
    initMap() {
      let that = this;
      let mapStr = this.str;
      let targetMap = document.getElementById(mapStr+"-map");
      if(targetMap.innerHTML!=""){
        console.log("清空targetMap");
      }
      targetMap.innerHTML = "";//清空
      //自动获取地图div高度
      this.autodivheight();
      //浏览器窗口发生变化时同时变化DIV高度
      window.onresize=this.autodivheight;
      if(this.map){//避免重复加载地图
        console.log("避免重复加载地图");
        return;
      }
      console.log("初始化地图");
      //获取投影4490坐标系
      this.projection4490 = getProjection();
      //初始化地图信息
      this.map = new Map({
        target: targetMap.id,
        /*controls: defaultControls({attributionOptions: {collapsed: false}})
            .extend([new Logo()]),*/
        view: new View({
          center: this.center,
          maxZoom: 18,
          minZoom: 3,
          zoom: this.zoom,
          constrainResolution:true,//缩放地图可移动到最近的缩放级别（整数zoom级别）
          projection: 'EPSG:4490',
          // resolutions:getResolutions()
        })
      });
      console.log("this.map");
      console.log(this.map);

      //新建工程查询结果图层
      this.xjAllDataVectorLayer = new VectorLayer({
        source: new VectorSource({
          wrapX: false
        }),
        projection: 'EPSG:4490'
      });
      this.map.addLayer(this.xjAllDataVectorLayer);
      this.xjAllDataVectorLayer.setZIndex(10);

      //加固工程查询结果图层
      this.jgAllDataVectorLayer = new VectorLayer({
        source: new VectorSource({
          wrapX: false
        }),
        projection: 'EPSG:4490'
      });
      this.map.addLayer(this.jgAllDataVectorLayer);
      this.jgAllDataVectorLayer.setZIndex(10);

      //地图对象传递
      this.$emit("getMap",this.map);
    },
    autodivheight() {//自动获取div高度
      //获取浏览器窗口高度
      let winHeight = 0;
      if (window.innerHeight) {
        winHeight = window.innerHeight;
      } else if ((document.body) && (document.body.clientHeight)) {
        winHeight = document.body.clientHeight;
      }
      //通过深入Document内部对body进行检测，获取浏览器窗口高度
      if (document.documentElement && document.documentElement.clientHeight) {
        winHeight = document.documentElement.clientHeight;
      }
      //全屏时窗口高度:941px,地图div高度:570px
      let tempHeight = 941;
      let mapTempHeight = 570;
      let mapHeight = winHeight - tempHeight + mapTempHeight;
      /*//最小高度
      if(mapHeight<480){
        mapHeight = 480;
      }*/
      //设置地图高度
      document.getElementById(this.str+"-map").style.height= mapHeight +"px";
      console.log("窗口高度："+winHeight+"地图高度："+mapHeight);
      //resize事件--刷新地图,确保地图不变形
      if(this.map){
        this.map.updateSize();
        console.log("resize事件--刷新地图,确保地图不变形");
      }
    },
    getPointStyle(){// 点图标样式
      let style = new Style({
        image: new Icon({
          src: dingweiImg,
          anchor: [0.5, 1]
        }),
      });
      return style;
    },
    getPointStyleByColor(fillColor,radius){//圆点样式
      let style = null;
      if(radius==null){
        radius = 2;
      }
      style = new Style({
        image: new CircleStyle({
          radius: radius,
          fill: new Fill({
            color: fillColor,
          }),
        })
      });

      return style;
    },
    getLineStringStyle(color,fillColor,width){//线样式
      if(fillColor!=null){
        //填充样式
      }else{
        fillColor = "rgba(0,0,0,0)";
      }
      if(width!=null){
        //线宽度
      }else{
        width = 2;
      }
      let style = new Style({
        fill:new Fill({//填充样式
          color:fillColor
        }),
        stroke:new Stroke({//描绘
          width:width,//宽
          color:color
        }),
        zIndex: 100
      });
      return style;
    },
    getPolyonStyle(color,fillColor,width){//多边形样式
      if(fillColor!=null){
        //填充样式
      }else{
        fillColor = "rgba(0,0,0,0)";
      }
      if(width!=null){
        //线宽度
      }else{
        width = 2;
      }
      let style = new Style({
        fill:new Fill({//填充样式
          color:fillColor
        }),
        stroke:new Stroke({//描绘
          width:width,//宽
          color:color
        }),
        zIndex: 100
      });
      return style;
    },
    getSelectPolyonStyle(){//选中要素样式
      let style = new Style({
        fill:new Fill({//填充样式
          color:"rgba(255,255,255,0.2)"
        }),
        stroke:new Stroke({//描绘
          width:2,//宽
          color:"rgba(30,144,255,1)"
        })
      });
      return style;
    },
    showBoundingExtent(coordinates){//缩放到区域位置
      console.log("缩放到区域位置");
      if (coordinates!=null && coordinates.length > 1) {
        const extent = boundingExtent(coordinates);
        //this.map.getView().fit(extent, {duration: 1000, padding: [50, 50, 50, 50]});
        this.map.getView().fit(extent, {padding: [50, 50, 50, 50]});
        //获取默认位置
        this.center = this.map.getView().getCenter();
        this.zoom = this.map.getView().getZoom();
      }
    },
    //处理经纬度
    getLonLat(longitude,latitude){
      let lonlat = null;
      if(longitude!=null && latitude!=null && longitude!="" && latitude!=""){
        let lon = Number(longitude);
        let lat = Number(latitude);
        if(lon>0 && lon<180 && lat>0 && lat<90){
          lonlat = [lon,lat];
        }
      }

      return lonlat;
    },
    showXjAllDataList(){//显示新建工程查询结果列表
      if(this.xjAllDataVectorLayer!=null) {
        this.xjAllDataVectorLayer.getSource().clear();//清空
        let list = this.xjAllDataList;
        if(list!=null && list.length>0){
          for(let i=0;i<list.length;i++){
            let data = list[i];
            //处理经纬度
            let lonlat = this.getLonLat(data.longitude,data.latitude);
            if(lonlat!=null){
              //点
              let featureTmp = new Feature({
                geometry: new Point(lonlat)
              });
              //样式
              let style = this.getPointStyleByColor("rgb(0,255,255)",5);//圆点样式
              featureTmp.setStyle(style);
              //设置属性
              featureTmp.setProperties({
                // longitude:data.longitude,
                // latitude:data.latitude,
                name:data.engineeringName,
                range:data.engineeringRange,
                type:data.engineeringType,
                photo:data.completionAcceptancePhoto,
                image:data.completionAcceptancePhoto,
                id:data.id,
              });
              //添加要素
              this.xjAllDataVectorLayer.getSource().addFeature(featureTmp);
            }
          }
        }
      }
    },
    showJgAllDataList(){//显示加固工程查询结果列表
      if(this.jgAllDataVectorLayer!=null) {
        this.jgAllDataVectorLayer.getSource().clear();//清空
        let list = this.jgAllDataList;
        if(list!=null && list.length>0){
          for(let i=0;i<list.length;i++){
            let data = list[i];
            //处理经纬度
            let lonlat = this.getLonLat(data.longitude,data.latitude);
            if(lonlat!=null){
              //点
              let featureTmp = new Feature({
                geometry: new Point(lonlat)
              });
              //样式
              let style = this.getPointStyleByColor("rgb(230,89,87)",5);//圆点样式
              featureTmp.setStyle(style);
              //设置属性
              featureTmp.setProperties({
                // longitude:data.longitude,
                // latitude:data.latitude,
                name:data.engineeringName,
                range:data.engineeringRange,
                type:data.engineeringType,
                photo:data.completionAcceptancePhoto,
                image:data.completionAcceptancePhoto,
                id:data.id,
              });
              //添加要素
              this.jgAllDataVectorLayer.getSource().addFeature(featureTmp);
            }
          }
        }
      }
    },
  }
}

</script>

<style lang="scss" scoped>
#indexMap-map{
  width: 100%;
  height: 100%;
}
</style>